﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using spbtzb;
using System.Text;

public partial class MessageBoard_MsgMgr : System.Web.UI.Page
{
    private Boolean session_Logined
    {
        set
        {
            Session["Logined"] = value;
        }
        get
        {
            return Session["Logined"] == null ? false : Convert.ToBoolean(Session["Logined"]);
        }
    }

    private string view_SortDirection
    {
        get
        {
            return ViewState["SortDirection"] == null ? "ASC" : Convert.ToString(ViewState["SortDirection"]);
        }
        set
        {
            ViewState["SortDirection"] = value;
        }
    }

    private string view_SortExpression
    {
        get
        {
            return ViewState["SortExpression"] == null ? String.Empty : Convert.ToString(ViewState["SortExpression"]);
        }
        set
        {
            ViewState["SortExpression"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (session_Logined == false)
            {
                Response.Redirect("~/Back/Login.aspx?ErrorMessage=" + "您未登录，请在此登录");
            }
            GVD_DataBind();
        }

    }

    protected void GVD_DataBind()
    {
        String strCount = "0";
        // generate datatable                       
        String strCmd = "SELECT * FROM MsgBrd";
        DataTable dt = AccessHelper.ExecuteDataTable(spbtzb.ConString.ConnString, CommandType.Text, strCmd);
        if (dt == null || dt.Rows.Count == 0)
        {
            btn_Auditing.Visible = false;
            ipt_HdnSelectedValues.Value = ",";
            this.gv_MsgList.DataSource = dt;
            this.gv_MsgList.DataBind();
            return;
        }
    
        btn_Auditing.Visible = true;
        StringBuilder sb = new StringBuilder();
        sb.Append(",");
        foreach (DataRow dr in dt.Rows)
        {
            if (dr["Status"] != null && Convert.ToBoolean(dr["Status"]) == true
                && dr["ID"] != null)
            {
                sb.Append(dr["ID"].ToString() + ",");
            }
        }
        if (sb.Length > 0)
        {
            this.ipt_HdnSelectedValues.Value = sb.Remove(sb.Length - 1, 1).ToString(); // 干掉最后一个逗号
        }       

        this.lbl_Count.Text = dt.Rows.Count.ToString();

        view_SortExpression = "CreateTime";
        view_SortDirection = "DESC";
        this.gv_MsgList.PageIndex = 0;
        this.gv_MsgList.DataSource = SortDataTable(dt as DataTable, true);
        this.gv_MsgList.DataBind();

        //strCmd = "SELECT count(*)  FROM MsgBrd";
        //Object ob = AccessHelper.ExecuteScalar(ConString.ConnString, CommandType.Text, strCmd);
        //if (ob == null || !spbtzb.AuthenCtr.IsInt(ob.ToString()))
        //{
        //    return;
        //}
        //else
        //{
        //    strCount = ob.ToString();
        //    this.lbl_Count.Text = strCount;
        //    //分页
        //}
 
    }

    protected void gv_MsgList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {        
        String strCmd = "SELECT * FROM MsgBrd";
        DataTable dt = AccessHelper.ExecuteDataTable(spbtzb.ConString.ConnString, CommandType.Text, strCmd);
        if (dt == null || dt.Rows.Count == 0)
        {
            return;
        }
        this.gv_MsgList.DataSource = SortDataTable(dt as DataTable, true); 
        //DataTable dt = (DataTable)gv_MsgList.DataSource;
        //gv_MsgList.DataSource = SortDataTable(gv_MsgList.DataSource as DataTable, true);
        gv_MsgList.PageIndex = e.NewPageIndex;
        gv_MsgList.DataBind();               
    }

    protected void btn_Auditing_Click(object sender, EventArgs e)
    {
        DataKeyArray dkCol = this.gv_MsgList.DataKeys;
        int index = 0;
        long lID = 0;

        string sqlCmd = "";
        int iRet = -1;

        foreach (GridViewRow dr in this.gv_MsgList.Rows)
        {
            CheckBox cbOld = (CheckBox)dr.FindControl("cb_AuditingTemp");
            HtmlInputCheckBox cbNew = (HtmlInputCheckBox)dr.FindControl("cb_Auditing");
            if (cbOld.Checked != cbNew.Checked )
            {
                // 获得该行的数据    
                index = dr.RowIndex;
                lID = Convert.ToInt64(dkCol[index].Value);
                if (lID == 0)
                {
                    // 跳转到错误处理页面
                    Response.Redirect("~/Common/ErrorPage.aspx?ErrorMessage="
                        + "审核留言失败，请重新操作或联系管理员!");
                }
                Boolean bStatus = cbNew.Checked;
                sqlCmd = String.Format("Update MsgBrd SET Status = {0} WHERE ID = {1}", bStatus, lID);
                iRet = AccessHelper.ExecuteNonQuery(ConString.ConnString, System.Data.CommandType.Text, sqlCmd);
                if (iRet > 0)
                {
                    continue;
                }
                else
                {
                    // 跳转到错误处理页面
                    Response.Redirect("~/Common/ErrorPage.aspx?ErrorMessage="
                        + "审核留言失败，请重新操作或联系管理员!");
                }
            }
            else
            {
 
            }
        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('审核成功！');", true); 
       // RegisterClientScriptBlock("tip", "<script>alert('审核成功！');window.location.href=window.location.href;</script>");

    }

    protected void btn_Del_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(UpdatePanel1, typeof(Button), "tip", "confirm(您真的要删除这篇留言吗？);", true); 
        // 获取当前选择的index
        Button btn = (Button)sender;
        DataControlFieldCell dv = (DataControlFieldCell)btn.Parent;
        GridViewRow gvr = (GridViewRow)dv.Parent;
        int index = gvr.RowIndex;

        GridView gv = (GridView)gvr.Parent.Parent; // GridViewRow的Parent是GridView.ChildTable

        DataKeyArray dkCol = gv.DataKeys;
        long lID = Convert.ToInt64(dkCol[index].Value);
        if (lID < 0)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('删除操作失败,请重新操作或联系管理员');window.location.href=window.location.href;", true); 
            //Response.Write("<script>alert('删除操作失败,请重新操作或联系管理员');window.location.href=window.location.href;</script>");
            return;
        }

        string sqlCmd = String.Format("DELETE * FROM MsgBrd WHERE ID = {0} ", lID);
        int iRet = AccessHelper.ExecuteNonQuery(spbtzb.ConString.ConnString, System.Data.CommandType.Text, sqlCmd);
        if (iRet < 0)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('删除操作失败,请重新操作或联系管理员');window.location.href=window.location.href;", true); 
            //Response.Write("<script>alert('删除操作失败,请重新操作或联系管理员');window.location.href=window.location.href;</script>");
            return;
        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "tip", "alert('删除操作成功!');", true);
        String strSelected = this.ipt_HdnSelectedValues.Value;
        String strTemp = "," + lID;
        if (strSelected.Contains(strTemp))
        {
            this.ipt_HdnSelectedValues.Value = strSelected.Replace(strTemp, "");
        }
        // RegisterClientScriptBlock("remind", "<script>alert('haha操作成功了！')</script>");
        //Response.Write("<script>alert('删除操作成功！');window.location.href=window.location.href;</script>");
   
        // edited by shiney __ rebind the gridview
        String strCmd = "SELECT * FROM MsgBrd";
        DataTable dt = AccessHelper.ExecuteDataTable(spbtzb.ConString.ConnString, CommandType.Text, strCmd);
        if (dt == null || dt.Rows.Count == 0)
        {
            btn_Auditing.Visible = false;
            ipt_HdnSelectedValues.Value = ",";
            this.gv_MsgList.DataSource = dt;
            this.gv_MsgList.DataBind();          
            return;
        }
        int iPageIndex = gv_MsgList.PageIndex;
        this.gv_MsgList.DataSource = SortDataTable(dt as DataTable, true);        
        this.gv_MsgList.PageIndex = iPageIndex;
        this.gv_MsgList.DataBind();  
    }

    protected void gv_MsgList_Sorting(object sender, GridViewSortEventArgs e)
    {
        String strCmd = "SELECT * FROM MsgBrd";
        DataTable dt = AccessHelper.ExecuteDataTable(spbtzb.ConString.ConnString, CommandType.Text, strCmd);
        if (dt == null || dt.Rows.Count == 0)
        {
            return;
        }

        view_SortExpression = e.SortExpression;     
        this.gv_MsgList.DataSource = SortDataTable(dt as DataTable, false);    

        int iPageIndex = gv_MsgList.PageIndex;    
        this.gv_MsgList.PageIndex = iPageIndex;
        this.gv_MsgList.DataBind();        
    }

    private string GetSortDirection()
    {
        switch (view_SortDirection)
        {
            case "ASC":
                view_SortDirection = "DESC";
                break;

            case "DESC":
                view_SortDirection = "ASC";
                break;
        }
        return view_SortDirection;
    }

    protected DataView SortDataTable(DataTable dataTable, bool isPageIndexChanging) 
    {
        if (dataTable != null)
        {
            DataView dataView = new DataView(dataTable);
            if (view_SortExpression != String.Empty)        
            {
                if (isPageIndexChanging)
                {
                    dataView.Sort = string.Format("{0} {1}", view_SortExpression, view_SortDirection);
                }
                else
                {
                    dataView.Sort = string.Format("{0} {1}", view_SortExpression, GetSortDirection());
                }
            }
            return dataView;
        }
        else
        {
            return new DataView();
        }
    }

    /// <summary>
    /// 综合考虑效率，干掉
    /// </summary>
    /// <param name="dataSource"></param>
    /// <returns></returns>
    private DataTable ConvertIEnumerableToDataTable(IEnumerable dataSource)
    {
        System.Reflection.PropertyInfo[] propInfo = null;
        DataTable dt = new DataTable();

        foreach (object o in dataSource)
        {
            propInfo = o.GetType().GetProperties();

            for (int i = 0; i < propInfo.Length; i++)
            {
                dt.Columns.Add(propInfo[i].Name);
            }
            break;
        }

        foreach (object tempObject in dataSource)
        {
            DataRow dr = dt.NewRow();
            for (int i = 0; i < propInfo.Length; i++)
            {
                object t = tempObject.GetType().InvokeMember(propInfo[i].Name, System.Reflection.BindingFlags.GetProperty, null, tempObject, new object[] { });
                if (t != null)
                    dr[i] = t.ToString();
            }
            dt.Rows.Add(dr);
        }
        return dt;
    }



    protected void gv_MsgList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.DataItemIndex < 0) return;
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // 来个垃圾办法解决问题
            HtmlInputCheckBox ChkSelected = (HtmlInputCheckBox)e.Row.FindControl("cb_Auditing");
            if (ChkSelected == null) return;
            String strid = ChkSelected.Value;
            String strIDs = this.ipt_HdnSelectedValues.Value;
            String strIDsEx = strIDs.TrimStart(',');
            String[] ids = strIDsEx.Split(',');
            foreach (String id in ids)
            {
                if (strid == id)
                {                    
                    ChkSelected.Checked = true;
                    return; 
                }
            }
        }
    }
}
